/**
 * @FileDescription 地图相关操作
 * @Author 祝小文
 * @Date 2022-10-09 10:02
 */

import red_add from '@/assets/image/mapIcon/red_add.png'
import redCircle from '@/assets/image/mapIcon/redCircle.png'
import { ElMessage } from 'element-plus'
import { createOverlay, createPoint, createRect, createScrollWall } from './createMapFactor'
import { useChemicalStore } from '@/store'
const chemicalStore = useChemicalStore()

/** 地图要素点击监听 */
export function loadFeatureClick() {
  const viewer = window.map3DControl.viewer

  // debugger

  window.CgsSubPub.subscribe(
    'leftdown',
    function (e: { timeStamp: number; type: string }, position: { x: number; y: number }) {
      // alert('leftdown')
      const pickedFeature = window.map.map3D.scene.pick(position)
    }
  )

  // viewer.screenSpaceEventHandler.setInputAction(function (event: any) {
  //   // 判断是否在模型上绘制
  //   debugger
  //   const pickedObject = viewer.scene.pick(event.position)
  //   if (Cesium.defined(pickedObject)) {
  //     if (!pickedObject.id || pickedObject.id.feature) {
  //     }
  //   }
  // }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
}

/** 地图要素创建 */
export function featureClick(obj: any) {
  //鼠标变成加号 颜色为红色
  document.getElementById('cesiumContainer').style.cursor = `url('${red_add}') 16 16, crosshair`

  //打开提示标牌，保存当前标注要素信息
  chemicalStore.tipsPageShow = true
  chemicalStore.currentFactorInfo.id = obj.id
  chemicalStore.currentFactorInfo.name = obj.MapFactorName
  chemicalStore.currentFactorInfo.type = obj.MapFactorType
  chemicalStore.currentFactorInfo.bzlx = obj.bzlx
  chemicalStore.currentFactorInfo.attribute = obj.attribute

  //围栏需要绘制多个点 走另外一个方法
  if (obj.MapFactorType === 'scrollWall') {
    rightClickProcess(obj)
  } else {
    leftClickProcess(obj)
  }
}

/** 左击绘制过程 */
function leftClickProcess(option: any) {
  const viewer = window.map3DControl.viewer
  viewer.screenSpaceEventHandler.setInputAction(function (event: any) {
    let cartesian
    //判断是否在模型上
    const pickedObject = viewer.scene.pick(event.position)
    if (Cesium.defined(pickedObject)) {
      //在模型上
      console.log('模型上')
      cartesian = viewer.scene.pickPosition(event.position)
    } else {
      //在模型外
      console.log('模型外')
      const ray = viewer.camera.getPickRay(event.position)
      cartesian = viewer.scene.globe.pick(ray, viewer.scene)
    }
    //如果没拾取到位置直接返回
    if (!cartesian) {
      return
    }

    //笛卡尔转经纬度
    const cartographic = Cesium.Cartographic.fromCartesian(cartesian)
    const lat = Cesium.Math.toDegrees(cartographic.latitude)
    const lng = Cesium.Math.toDegrees(cartographic.longitude)
    const alt = cartographic.height

    //保存要素位置信息
    chemicalStore.currentFactorInfo.wzxx = { lng, lat, alt }
    //保存要素中心点经度纬度
    chemicalStore.currentFactorInfo.zxdjdwd = { lng, lat, alt }

    //消防设施和企业设施中的要素 不需要弹出二次确认框
    if (option.attribute?.parentId === 'ys00001' || option.attribute?.parentId === 'ys00002') {
      chemicalStore.currentMenuParentId = option.attribute.parentId
      return
    }

    //标牌
    if (option.MapFactorType === 'overlay') {
      createOverlay({
        id: option.id,
        parentName: option.parentName,
        text: option.text,
        iconUrl: option.mapIconUrl,
        bzlx: option.bzlx,
        parentMenuId: option.parentMenuId,
        pos: [lng, lat, alt],
        attribute: { zxjd: lng, zxwd: lat, zxgd: alt },
      })
      console.log('创建标牌')
    }
    //点图标
    else if (option.MapFactorType === 'point') {
      createPoint({
        id: option.id,
        parentName: option.parentName,
        iconUrl: option.mapIconUrl,
        bzlx: option.bzlx,
        pos: [lng, lat, alt],
        attribute: { zxjd: lng, zxwd: lat, zxgd: alt },
      })
      console.log('创建点图标')
    }
    //路宽
    else if (option.MapFactorType === 'rect') {
      createRect({
        id: option.id,
        parentName: option.parentName,
        iconUrl: option.mapIconUrl,
        bzlx: option.bzlx,
        pos: { lng, lat, height: alt },
        attribute: { zxjd: lng, zxwd: lat, zxgd: alt },
      })
      console.log('创建路宽')
    }

    chemicalStore.tipsPageShow = false //关闭提示标牌
    chemicalStore.FactorConfirmShow = true //打开要素保存二次确认弹窗

    clearEditState() //清除标注状态
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
}

/** 右击绘制过程 */
function rightClickProcess(option: any) {
  const viewer = window.map3DControl.viewer
  let gatherScrollWall: any = null
  const pointArr: any = []
  viewer.screenSpaceEventHandler.setInputAction(function (event: any) {
    let cartesian
    // 判断是否在模型上绘制
    const pickedObject = viewer.scene.pick(event.position)
    if (Cesium.defined(pickedObject)) {
      //在模型上
      cartesian = window.map3DControl.viewer.scene.pickPosition(event.position)
    } else {
      //在模型外
      const ray = viewer.camera.getPickRay(event.position)
      cartesian = viewer.scene.globe.pick(ray, viewer.scene)
    }
    //如果没拾取到位置直接返回
    if (!cartesian) {
      return
    }

    //笛卡尔坐标转经纬度坐标
    const ellipsoid = viewer.scene.globe.ellipsoid
    const cartographic = ellipsoid.cartesianToCartographic(cartesian)
    const obj = { lat: 0, lng: 0, alt: 0 }
    obj.lat = Cesium.Math.toDegrees(cartographic.latitude)
    obj.lng = Cesium.Math.toDegrees(cartographic.longitude)
    obj.alt = cartographic.height
    pointArr.push([obj.lng, obj.lat, obj.alt])

    //辅助点
    window.GPoint.add({
      parentName: 'auxiliaryPoint',
      option: {
        position: [obj.lng, obj.lat, obj.alt],
        scale: 0.1,
        url: redCircle,
        pixelOffset: [0, 0],
      },
    })

    if (pointArr.length >= 3) {
      if (gatherScrollWall == null) {
        gatherScrollWall = createScrollWall({
          id: option.id,
          parentName: option.parentName,
          text: option.text,
          bzlx: option.bzlx,
          pos: pointArr,
        })
      } else {
        //修改围栏位置
        gatherScrollWall[0].setPositions(pointArr)
        //修改围栏标注位置
        const cenPos = calCulatePosCenter(pointArr)
        cenPos[2] = cenPos[2] + 10

        gatherScrollWall[1].setPosition(cenPos)
      }
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

  viewer.screenSpaceEventHandler.setInputAction(function () {
    // 如果小于四个点就结束绘制则提示用户
    if (pointArr.length < 4) {
      return ElMessage.warning('最少绘制四个点')
    }

    //移除辅助点
    window.GPoint.removeByPatName('auxiliaryPoint')

    //保存要素位置信息
    chemicalStore.currentFactorInfo.wzxx = pointArr
    const cenPos = calCulatePosCenter(pointArr)
    //保存要素中心点经度纬度
    chemicalStore.currentFactorInfo.zxdjdwd = {
      lng: cenPos[0],
      lat: cenPos[1],
      alt: cenPos[2] + 10,
    }

    //更新围栏在地图中的中心点经度纬度
    gatherScrollWall[0].feature3D.attribute = {
      zxjd: cenPos[0],
      zxwd: cenPos[1],
      zxgd: cenPos[2] + 10,
    }

    chemicalStore.tipsPageShow = false //关闭提示标牌
    chemicalStore.FactorConfirmShow = true //打开要素保存二次确认弹窗

    clearEditState() //清除标注状态
  }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
}

/** 传入经纬度计算中心点 */
function calCulatePosCenter(pos: any) {
  let xAxios = 0,
    yAxios = 0,
    zAxios = 0,
    cenPos
  pos.forEach((item: any) => {
    xAxios += item[0]
    yAxios += item[1]
    zAxios += item[2]
  })
  cenPos = [xAxios / pos.length, yAxios / pos.length, zAxios / pos.length]
  return cenPos
}

/** 清除标注状态 */
export function clearEditState() {
  const viewer = window.map3DControl.viewer

  chemicalStore.tipsPageShow = false //关闭提示标牌

  document.getElementById('cesiumContainer').style.cursor = 'default'
  //移除地图点击事件
  viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
  viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK)
}

/** 根据类型和采集id定位 */
export function flyToLxOrCjid(mapFactorType: any, cjId: any) {
  const pos: any = {}
  switch (mapFactorType) {
    case 'overlay':
      window.GOverlayArray.forEach((item: any) => {
        if (item.name === cjId) {
          const { zxjd, zxwd, zxgd } = item.overlay.attribute
          pos.lng = zxjd
          pos.lat = zxwd
          pos.height = zxgd + 100
        }
      })
      break
    case 'point':
      window.GPointArray.forEach((item: any) => {
        if (item.name === cjId) {
          const { zxjd, zxwd, zxgd } = item.point.feature3D.attribute
          pos.lng = zxjd
          pos.lat = zxwd
          pos.height = zxgd + 50
        }
      })
      break
    case 'rect':
      window.GCgsRectArray.forEach((item: any) => {
        if (item.name === cjId) {
          const { zxjd, zxwd, zxgd } = item.imageRect.feature3D.attribute
          pos.lng = zxjd
          pos.lat = zxwd
          pos.height = zxgd + 150
        }
      })
      break
    case 'scrollWall':
      window.GScrollWallArray.forEach((item: any) => {
        if (item.name === cjId) {
          const { zxjd, zxwd, zxgd } = item.scrollWall.feature3D.attribute
          pos.lng = zxjd
          pos.lat = zxwd
          pos.height = zxgd + 200
        }
      })
      break
  }

  if (Object.keys(pos).length > 0 && pos.lng) {
    window.GCamera.flyTo({
      pos,
    })
  }
}
